#!/usr/local/bin/php
<?php
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');

require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';
require_once OPEN_LIB_PATH . '/open/models/OaAppConfigOrderModel.php';

$logger = Log::factory('console', '', '', array(
    'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
    'timeFormat' => '%Y-%m-%d %H:%M:%S'
), PEAR_LOG_INFO);
$logger->setPriority(PEAR_LOG_INFO);

$options = getopt('a:f:d');
if (empty($options)) {
    $logger->err("usage: " . basename(__FILE__) . " [-f app_list_file|-a app_id] [-d]");
    exit();
}
if (isset($options['f'])) {
    $contents = file_get_contents($options['f']);
    if ($contents === false) {
        $logger->err("get file contents failed");
        exit();
    }
} else if (isset($options['a'])) {
    $contents = $options['a'];
} else {
    $logger->err("no app specified");
    exit();
}
$delete = false;
if (isset($options['d'])) {
	$delete = true;
}

$appCfgOrdMod = new OaAppConfigOrderModel($logger);
$rows = explode("\n", trim($contents));
foreach ($rows as $row) {
    $row = explode("\t", trim($row));
    $appId = isset($row[0]) ? intval($row[0]) : 0;
    if ($appId < 0) {
        $logger->warning("app id invalid: app_id-$appId");
        continue;
    }
    $order = $appCfgOrdMod->getAppLastConfigOrder($appId);
    if (!$order) {
    	$logger->warning("get last order failed: app-$appId");
        continue;
    }
    $orderId = $order['id'];
    $envs = array(OaAppModel::APP_CONFIG_ENV_TEST, OaAppModel::APP_CONFIG_ENV_PRODUCTION);
    foreach ($envs as $env) {
    	$snapshot = $appCfgOrdMod->getAppSnapshot($orderId, $env, array('basic_info'));
    	if ($snapshot) {
    		if ($delete == true) {
    			if ($appCfgOrdMod->deleteAppSnapshot($orderId, $env)) {
    				$logger->info("delete snapshot succeed: order-$orderId, env-$env");
    			} else {
    				$logger->warning("delete snapshot failed: order-$orderId, env-$env");
                    continue;
    			}
    		} else {
    			$logger->warning("snapshot already exits: order-$orderId, env-$env");
                continue;
    		}
    	}
    	if ($appCfgOrdMod->addAppSnapshot($orderId, $env)) {
    		$logger->info("add snapshot succeed: order-$orderId, env-$env");
    	} else {
    		$logger->warning("add snapshot failed: order-$orderId, env-$env");
            continue;
    	}
    }
}
